package com.mls.fivedistrict.exception;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.mls.fivedistrict.common.ServiceResponse;
import com.mls.fivedistrict.enums.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义异常处理类
 * Created by chenxiuxiang on 2017/12/30.
 */
@Slf4j
public class CustomerExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        if (e instanceof CustomerException || e instanceof ParamException) {
            ModelAndView mv = new ModelAndView();
            try {
                httpServletResponse.setCharacterEncoding("utf-8");
                httpServletResponse.setContentType("text/html;charset=utf-8");
                PrintWriter printWriter = httpServletResponse.getWriter();
                String message = e.getMessage();
                ServiceResponse serviceResponse;
                if (message.equals("请登录")) {
                    serviceResponse = ServiceResponse.createErrorResponse(ResponseCode.NEED_LOGIN.getCode(), message);
                } else {
                    serviceResponse = ServiceResponse.createErrorResponse(message);
                }
                ObjectMapper objectMapper = new ObjectMapper();
                String response = objectMapper.writeValueAsString(serviceResponse);
                printWriter.write(response);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return mv;
        } else {
            ModelAndView mv = new ModelAndView();
            try {
                System.out.println("系统错误：" + e.getMessage());
                httpServletResponse.setCharacterEncoding("utf-8");
                httpServletResponse.setContentType("text/html;charset=utf-8");
                PrintWriter printWriter = httpServletResponse.getWriter();
                String message = "系统错误";
                String detail = e.getMessage();
                ServiceResponse serviceResponse = ServiceResponse.createErrorResponse(message, detail);
                ObjectMapper objectMapper = new ObjectMapper();
                String response = objectMapper.writeValueAsString(serviceResponse);
                printWriter.write(response);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return mv;
        }
    }
}
